
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Request;
function i_array_column($input, $columnKey, $indexKey = null)
{
    if (!function_exists('array_column')) {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
        $indexKeyIsNull = (is_null($indexKey)) ? true : false;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
        $result = array();
        foreach ((array)$input as $key => $row) {
            if ($columnKeyIsNumber) {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
            } else {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
            }
            if (!$indexKeyIsNull) {
                if ($indexKeyIsNumber) {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key)) ? current($key) : null;
                    $key = is_null($key) ? 0 : $key;
                } else {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }
            $result[$key] = $tmp;
        }
        return $result;
    } else {
        return array_column($input, $columnKey, $indexKey);
    }
}

/**
 * @param $arr
 * @param $offset
 * @param int $length
 * @return array
 * @description 删除数组中的特定元素
 */
function array_remove(&$arr, $offset, $length = 1)
{
    $arrNew = array_splice($arr, $offset, $length);
    return $arrNew;
}

/**
 * @param $v
 * @param array $arr
 * @return mixed
 * 过滤数组的元素
 */

function array_del_val($v, array $arr = array('.', '..', null))
{
    if (in_array($v, $arr)) {
        unset($v);
    }
    return $v;
}

/**
 * @param $file
 * @return mixed
 * 获取文件后缀
 */
function get_extension($file)
{
    $info = pathinfo($file);
    return $info['extension'];
}

/**
 * @param string $msg
 * @param array $fields
 */
function ajaxError($msg = '', $fields = array())
{
    header('Content-Type:application/json; charset=utf-8');
    $data = array('status' => 'error', 'msg' => $msg, 'fields' => $fields);
    echo json_encode($data);
    exit;
}

function Error($msg = '', $fields = array())
{
    header('Content-Type:application/json; charset=utf-8');
    $data = array('status' => 'error', 'msg' => $msg, 'fields' => $fields);
    dump($data);
    exit;
}

function ajaxReturnData($status = '', $data = array())
{
    header('Content-Type:application/json; charset=utf-8');
    $dataArr = array('status' => $status, 'data' => $data);
    echo json_encode($dataArr);
    exit;
}

/**
 * @param string $msg
 * @param array $fields
 * 验证不通过
 */
function ajaxVerifyError($msg = '', $fields = array())
{
    header('Content-Type:application/json; charset=utf-8');
    $data = array('status' => 'verify', 'msg' => $msg, 'fields' => $fields);
    echo json_encode($data);
    exit;
}

/**
 * @param $msg
 * @param array $_data
 */
function ajaxSuccess($msg, $_data = array())
{
    header('Content-Type:application/json; charset=utf-8');
    $data = array('status' => 'success', 'msg' => $msg, 'data' => $_data);
    echo json_encode($data);
    exit;
}

/**
 * @description: 递归菜单
 * @author: 554665488@qq.com(2016年8月7日)
 * @param array $array
 * @param number $fid
 * @param number $level
 * @param number $type 1:顺序菜单 2树状菜单
 * @return array:number
 */
function get_column($array, $type = 1, $fid = 0, $level = 0)
{
    $column = array();
    if ($type == 2) {
        foreach ($array as $key => $vo) {
            if ($vo['pid'] == $fid) {
                $vo['level'] = $level;
                $column[$key] = $vo;
                $column [$key][$vo['id']] = get_column($array, $type = 2, $vo['id'], $level + 1);
            }
        }
    } else {
        foreach ($array as $key => $vo) {
            if ($vo['pid'] == $fid) {
                $vo['level'] = $level;
                $column[] = $vo;
                $column = array_merge($column, get_column($array, $type = 1, $vo['id'], $level + 1));
            } else {
                //父级ID与一级pid=0相等的为为二级菜单
            }
        }
    }

    return $column;
}

/**
 * @param $array
 * @param int $type
 * @param int $parent_id
 * @return array
 * @description 递归获得角色列表
 */
function get_role_list($array, $type = 1, $parent_id = 0)
{
    $list = array();
    if ($type == 2) {

    } else {
        foreach ($array as $key => $vo) {
            if ($vo['role_pid'] == $parent_id) {
                $list[] = $vo;
                $list = array_merge($list, get_role_list($array, $type = 1, $vo['id']));
            }
        }
    }
    return $list;
}

function get_user_list($array, $parent_id = 0)
{
    $list = array();
    foreach ($array as $key => $vo) {
        if ($vo['parent_id'] == $parent_id) {
            $list[] = $vo;
            $list = array_merge($list, get_user_list($array, $vo['id']));
        }
    }
    return $list;
}

/**
 * @param $rule
 * @param $uid
 * @param int $ok
 * @param int $error
 * @return int
 * 判断权限
 */
function authCheck($rule, $uid, $ok = true, $error = false)
{
    $auth = new \Think\Auth();
    return $auth->check($rule, $uid) ? $ok : $error;
}

/**
 * +----------------------------------------------------------
 * 功能：原样输出print_r的内容
 * @param string $content 待print_r的内容
 * +----------------------------------------------------------
 */
function pre($content)
{
    echo "<pre>";
    dump($content);
    echo "</pre>";
    die;

}

/**
 * @param $number
 * @param int $num
 * @return string
 * 格式化数字
 */
function mj_number_format($number, $num = 2)
{
    if (strstr($number, '.')) {
        $p = stripos($number, '.');  //4

        $tmp = substr($number, 0, $p + 3);  //1000.00

    } else {
        $tmp = $number;
    }
    return number_format($tmp, $num);//number_format  通过千位数格式化字符串
}


/**
 * +----------------------------------------------------------
 * 功能：加密密码
 * @param string $data 待加密字符串
 * @return string 返回加密后的字符串
 * +----------------------------------------------------------
 */
function encrypt($data)
{
    return md5(C("AUTH_CODE") . md5($data));
}

/**
 * +----------------------------------------------------------
 * 功能：将一个字符串转换成数组，支持中文
 * @param string $string 待转换成数组的字符串
 * @return string   转换后的数组
 * +----------------------------------------------------------
 */
function strToArray($string)
{
    $strlen = mb_strlen($string);
    while ($strlen) {
        $array[] = mb_substr($string, 0, 1, "utf8");
        $string = mb_substr($string, 1, $strlen, "utf8");
        $strlen = mb_strlen($string);
    }
    return $array;
}

/**
 * +----------------------------------------------------------
 * 功能：生成随机字符串
 * @param int $length 要生成的随机字符串长度
 * @param string $type 随机码类型：0，数字+大写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符
 * @return string
+----------------------------------------------------------
 */
function randCode($length = 5, $type = 0)
{
    $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");
    if ($type == 0) {
        array_pop($arr);
        $string = implode("", $arr);
    } else if ($type == "-1") {
        $string = implode("", $arr);
    } else {
        $string = $arr[$type];
    }
    $count = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        $str[$i] = $string[rand(0, $count)];
        $code .= $str[$i];
    }
    return $code;
}

/**
 * +-----------------------------------------------------------------------------------------
 * 功能：删除目录及目录下所有文件或删除指定文件
 * @param str $path 待删除目录路径
 * @param int $delDir 是否删除目录，1或true删除目录，0或false则只删除文件保留目录（包含子目录）
 * @return bool 返回删除状态
 * +-----------------------------------------------------------------------------------------
 */
function delDirAndFile($path, $delDir = FALSE)
{
    $handle = opendir($path);
    if ($handle) {
        while (false !== ($item = readdir($handle))) {
            if ($item != "." && $item != "..")
                is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
        }
        closedir($handle);
        if ($delDir)
            return rmdir($path);
    } else {
        if (file_exists($path)) {
            return unlink($path);
        } else {
            return FALSE;
        }
    }
}

/**
 * +----------------------------------------------------------
 * 功能：将一个字符串部分字符用*替代隐藏
 * @param string $string 待转换的字符串
 * @param int $bengin 起始位置，从0开始计数，当$type=4时，表示左侧保留长度
 * @param int $len 需要转换成*的字符个数，当$type=4时，表示右侧保留长度
 * @param int $type 转换类型：0，从左向右隐藏；1，从右向左隐藏；2，从指定字符位置分割前由右向左隐藏；3，从指定字符位置分割后由左向右隐藏；4，保留首末指定字符串
 * @param string $glue 分割符
 * @return string   处理后的字符串
 * +----------------------------------------------------------
 */
function hideStr($string, $bengin = 0, $len = 4, $type = 0, $glue = "@")
{
    if (empty($string))
        return false;
    $array = array();
    if ($type == 0 || $type == 1 || $type == 4) {
        $strlen = $length = mb_strlen($string);
        while ($strlen) {
            $array[] = mb_substr($string, 0, 1, "utf8");
            $string = mb_substr($string, 1, $strlen, "utf8");
            $strlen = mb_strlen($string);
        }
    }
    switch ($type) {
        case 1:
            $array = array_reverse($array);
            for ($i = $bengin; $i < ($bengin + $len); $i++) {
                if (isset($array[$i]))
                    $array[$i] = "*";
            }
            $string = implode("", array_reverse($array));
            break;
        case 2:
            $array = explode($glue, $string);
            $array[0] = hideStr($array[0], $bengin, $len, 1);
            $string = implode($glue, $array);
            break;
        case 3:
            $array = explode($glue, $string);
            $array[1] = hideStr($array[1], $bengin, $len, 0);
            $string = implode($glue, $array);
            break;
        case 4:
            $left = $bengin;
            $right = $len;
            $tem = array();
            for ($i = 0; $i < ($length - $right); $i++) {
                if (isset($array[$i]))
                    $tem[] = $i >= $left ? "*" : $array[$i];
            }
            $array = array_chunk(array_reverse($array), $right);
            $array = array_reverse($array[0]);
            for ($i = 0; $i < $right; $i++) {
                $tem[] = $array[$i];
            }
            $string = implode("", $tem);
            break;
        default:
            for ($i = $bengin; $i < ($bengin + $len); $i++) {
                if (isset($array[$i]))
                    $array[$i] = "*";
            }
            $string = implode("", $array);
            break;
    }
    return $string;
}

/**
 * +----------------------------------------------------------
 * 功能：字符串截取指定长度
 * leo.li hengqin2008@qq.com
 * @param string $string 待截取的字符串
 * @param int $len 截取的长度
 * @param int $start 从第几个字符开始截取
 * @param boolean $suffix 是否在截取后的字符串后跟上省略号
 * @return string               返回截取后的字符串
 * +----------------------------------------------------------
 */
function cutStr($str, $len = 100, $start = 0, $suffix = 1)
{
    $str = strip_tags(trim(strip_tags($str)));
    $str = str_replace(array("\n", "\t"), "", $str);
    $strlen = mb_strlen($str);
    while ($strlen) {
        $array[] = mb_substr($str, 0, 1, "utf8");
        $str = mb_substr($str, 1, $strlen, "utf8");
        $strlen = mb_strlen($str);
    }
    $end = $len + $start;
    $str = '';
    for ($i = $start; $i < $end; $i++) {
        $str .= $array[$i];
    }
    return count($array) > $len ? ($suffix == 1 ? $str . "&hellip;" : $str) : $str;
}

/**
 * +----------------------------------------------------------
 * 功能：检测一个目录是否存在，不存在则创建它
 * @param string $path 待检测的目录
 * @return boolean
+----------------------------------------------------------
 */
function makeDir($path)
{
    return is_dir($path) or (makeDir(dirname($path)) and @mkdir($path, 0777));
}

/**
 * +----------------------------------------------------------
 * 功能：检测一个字符串是否是邮件地址格式
 * @param string $value 待检测字符串
 * @return boolean
+----------------------------------------------------------
 */
function is_email($value)
{
    return preg_match("/^[0-9a-zA-Z]+(?:[\_\.\-][a-z0-9\-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\.[a-zA-Z]+$/i", $value);
}

/**
 * +----------------------------------------------------------
 * 功能：系统邮件发送函数
 * @param string $to 接收邮件者邮箱
 * @param string $name 接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
+----------------------------------------------------------
 */
function send_mail($to, $name, $subject = '', $body = '', $attachment = null, $config = '')
{
    $config = is_array($config) ? $config : C('SYSTEM_EMAIL');
    import('PHPMailer.phpmailer', VENDOR_PATH);         //从PHPMailer目录导class.phpmailer.php类文件
    $mail = new PHPMailer();                           //PHPMailer对象
    $mail->CharSet = 'UTF-8';                         //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();                                   // 设定使用SMTP服务
//    $mail->IsHTML(true);
    $mail->SMTPDebug = 0;                             // 关闭SMTP调试功能 1 = errors and messages2 = messages only
    $mail->SMTPAuth = true;                           // 启用 SMTP 验证功能
    if ($config['smtp_port'] == 465)
        $mail->SMTPSecure = 'ssl';                    // 使用安全协议
    $mail->Host = $config['smtp_host'];                // SMTP 服务器
    $mail->Port = $config['smtp_port'];                // SMTP服务器的端口号
    $mail->Username = $config['smtp_user'];           // SMTP服务器用户名
    $mail->Password = $config['smtp_pass'];           // SMTP服务器密码
    $mail->SetFrom($config['from_email'], $config['from_name']);
    $replyEmail = $config['reply_email'] ? $config['reply_email'] : $config['reply_email'];
    $replyName = $config['reply_name'] ? $config['reply_name'] : $config['reply_name'];
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($to, $name);
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            if (is_array($file)) {
                is_file($file['path']) && $mail->AddAttachment($file['path'], $file['name']);
            } else {
                is_file($file) && $mail->AddAttachment($file);
            }
        }
    } else {
        is_file($attachment) && $mail->AddAttachment($attachment);
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}

/**
 * 格式化字节大小
 * @param  number $size 字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * +----------------------------------------------------------
 * 功能：剔除危险的字符信息
 * @param string $val
 * @return string 返回处理后的字符串
 * +----------------------------------------------------------
 */
function remove_xss($val)
{
    // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
    // this prevents some character re-spacing such as <java\0script>
    // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
    $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

    // straight replacements, the user should never need these since they're normal characters
    // this prevents like <IMG SRC=@avascript:alert('XSS')>
    $search = 'abcdefghijklmnopqrstuvwxyz';
    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $search .= '1234567890!@#$%^&*()';
    $search .= '~`";:?+/={}[]-_|\'\\';
    for ($i = 0; $i < strlen($search); $i++) {
        // ;? matches the ;, which is optional
        // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
        // @ @ search for the hex values
        $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
        // @ @ 0{0,7} matches '0' zero to seven times
        $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
    }

    // now the only remaining whitespace attacks are \t, \n, and \r
    $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
    $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $ra = array_merge($ra1, $ra2);

    $found = true; // keep replacing as long as the previous round replaced something
    while ($found == true) {
        $val_before = $val;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = '/';
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= '(';
                    $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                    $pattern .= '|';
                    $pattern .= '|(&#0{0,8}([9|10|13]);)';
                    $pattern .= ')*';
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= '/i';
            $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
            $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
            if ($val_before == $val) {
                // no replacements were made, so exit the loop
                $found = false;
            }
        }
    }
    return $val;
}

/**
 * +----------------------------------------------------------
 * 功能：计算文件大小
 * @param int $bytes
 * @return string 转换后的字符串
 * +----------------------------------------------------------
 */
function byteFormat($bytes)
{
    $sizetext = array(" B", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
    return round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), 2) . $sizetext[$i];
}

/**
 * @param $string
 * @param string $charset
 * @return string|void
 * 修改字符串的编码
 */
function checkCharset($string, $charset = "UTF-8")
{
    if ($string == '')
        return;
    $check = preg_match('%^(?:
                                [\x09\x0A\x0D\x20-\x7E] # ASCII
                                | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
                                | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
                                | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
                                | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
                                | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
                                | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
                                | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
                                )*$%xs', $string);

    return $charset == "UTF-8" ? ($check == 1 ? $string : iconv('gb2312', 'utf-8', $string)) : ($check == 0 ? $string : iconv('utf-8', 'gb2312', $string));
}

/**
 * +----------------------------------------------------------
 * 功能：对象转换成PHP数组
 * @param array $objData 对象数据
 * @return array    转换后的php数组
 * +----------------------------------------------------------
 */
function objToArr($objData)
{
    $ret = array();
    foreach ($objData as $key => $value) {
        if (gettype($value) == 'array' || gettype($value) == 'object') {
            $ret[$key] = objToArr($value);
        } else {
            $ret[$key] = $value;
        }
    }
    return $ret;
}

/**
 * +----------------------------------------------------------
 * 功能：json数据转换成PHP数组
 * @param array $jsonData json数组数据
 * @return array    转换后的php数组
 * +----------------------------------------------------------
 */
function jsonToArr($jsonData)
{
    $objData = json_decode($jsonData);
    return objToArr($objData);
}

/**
 * +----------------------------------------------------------
 * 功能：时间转换为几天前
 * @param int $time 时间戳
 * @return string    转换后的字符串
 * +----------------------------------------------------------
 */
function timeFormat($time)
{
    $nowTime = time();
    $dur = $nowTime - $time;
    if ($dur < 0) {
        return $time;
    } else {
        if ($dur < 60) {
            return '<font color="red">' . $dur . '秒前</font>';
        } else {
            if ($dur < 3600) { //1小时内
                return '<font color="red">' . floor($dur / 60) . '分钟前</font>';
            } else {
                if ($dur < 86400) { //1天内
                    return '<font color="red">' . floor($dur / 3600) . '小时前</font>';
                } else {
                    if ($dur < 259200) {//3天内
                        return '<font color="red">' . floor($dur / 86400) . '天前</font>';
                    } else {
                        return date('Y-m-d H:i:s', $time);
                    }
                }
            }
        }
    }
}

/**
 * +----------------------------------------------------------
 * 功能：获取指定目录下所有文件夹及文件
 * @param  string $dir 路径
 * @return  string
+----------------------------------------------------------
 */
function getFileName($dir = 'E:/')
{
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) != false) {
                //文件名的全路径 包含文件名
                $filePath = $dir . $file;
                //获取文件修改时间
                $fmt = filemtime($filePath);
                echo "<span style='color:#666'>(" . date("Y-m-d H:i:s", $fmt) . ")</span> " . $filePath . "<br/>";
            }
            closedir($dh);
        }
    }
}

function getFileNameArray($dir = 'E:/')
{
    $arr = array();
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) != false) {
                //文件名的全路径 包含文件名
                $filePath = $dir . $file;
                //获取文件修改时间
//                $fmt = filemtime($filePath);
                $arr[] = $file;
            }
            closedir($dh);
        }
    }
//    dump($arr);
    return $arr;
}



/**
 * @param $str 必需。规定要检查的字符串。
 * @return string
 * @param $charlist 可选。规定从字符串中删除哪些字符。如果被省略，则移除以下所有字符："\0" - NULL "\t" - 制表符 "\n" - 换行 "\x0B" - 垂直制表符 "\r" - 回车 " " - 空格
 *
 */
function romoveTrim($str, $charlist = true)
{
    $str = null;
    if ($charlist == true) {
        $str = trim($str);
    } else {
        $str = trim($str, $charlist);
    }
    return $str;
}


//获取用户真实IP
/**
 * @return array|false|string
 */
function getIp()
{
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
    elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
        $ip = getenv("REMOTE_ADDR");
    elseif (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else
        $ip = "unknown";
    return ($ip);
}


/**
 * @param $num
 * @param int $decimals
 * @param string $decimalpoint
 * @param string $separator
 * @return string
 * @description 以千位分组来格式化数字。
 */
function i_number_format($num = '', $decimals = 2, $decimalpoint = '.', $separator = ",")
{

    if (strlen($num) > 0) {
        $number = number_format(trim($num), $decimals, $decimalpoint, $separator);
    } else {
        $number = $num;
    }
    return $number;
}

/**
 * 上传文件类型控制 此方法仅限ajax上传使用
 * @param  string $path 字符串 保存文件路径示例： /Upload/image/
 * @param  string $format 文件格式限制
 * @param  integer $maxSize 允许的上传文件最大值 52428800
 * @return booler   返回ajax的json格式数据
 */
function ajax_upload($path = 'file', $format = 'empty', $maxSize = '52428800')
{
    ini_set('max_execution_time', '0');
//    // 去除两边的/
//    $path=trim($path,'/');
//    // 添加Upload根目录
//    $path=strtolower(substr($path, 0,6))==='upload' ? ucfirst($path) : 'Upload/'.$path;
    // 上传文件类型控制
//    $ext_arr= array(
//        'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
//        'photo' => array('jpg', 'jpeg', 'png'),
//        'flash' => array('swf', 'flv'),
//        'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
//        'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
//    );
    $ext_arr = array(
        'gif', 'jpg', 'jpeg', 'png', 'bmp'
    );
    if (!empty($_FILES)) {
        // 上传文件配置
        $config = array(
            'maxSize' => $maxSize,               // 上传文件最大为50M
            'rootPath' => './',                   // 文件上传保存的根路径
            'savePath' => './' . $path . '/',         // 文件上传的保存路径（相对于根路径）
            'saveName' => array('uniqid', ''),     // 上传文件的保存规则，支持数组和字符串方式定义
            'autoSub' => true,                   // 自动使用子目录保存上传文件 默认为true
            'exts' => isset($ext_arr[$format]) ? $ext_arr[$format] : $ext_arr,
        );
        // 实例化上传
        $upload = new \Think\Upload($config);
        // 调用上传方法
        $info = $upload->upload();
        $data = array();
        if (!$info) {
            // 返回错误信息
            $error = $upload->getError();
            $data['error_info'] = $error;
            echo json_encode($data);
        } else {
            // 返回成功信息
            foreach ($info as $file) {
                $data['name'] = trim($file['savepath'] . $file['savename'], '.');
                echo json_encode($data);
            }
        }
    }
}

/**
 * @param string $path
 * @param string $type
 * @param string $maxSize
 * webupload 上传图片API
 */
function webUploadApi($path = '', $type = '', $maxSize = '32922000')
{

    $upload = new UploadFile();
    $upload->maxSize = $maxSize; //设置上传文件大小
    $upload->allowExts = explode(',', 'jpg,png,jpeg,gif'); //设置上传文件类型
    $upload->savePath = $path;//设置附件上传目录

    $upload->zipImages = false; //压缩图片上传
    $upload->autoSub = true;//开启子目录上传
    $upload->subType = 'date';//子目录方式
    //设置上传文件规则
    $upload->saveRule = 'uniqid';
    //删除原图
    $upload->thumbRemoveOrigin = false;
    if (!$upload->upload()) {
        //捕获上传异常
        header('Content-Type:application/json; charset=utf-8');
        $dataArr = array('status' => 0, 'error' => $upload->getErrorMsg());
        echo json_encode($dataArr);
        exit;
    } else {
        //取得成功上传的文件信息
        $uploadList = $upload->getUploadFileInfo();
        // 处理得到最小的thum图片
        $arr = explode('/', $uploadList[0]['savename']);
        $imgPath = substr($path, 1) . $arr[0] . '/' . $type . $arr[1];

        header('Content-Type:application/json; charset=utf-8');
        $dataArr = array('status' => 1, 'savePath' => $imgPath);
        echo json_encode($dataArr);
        exit;
    }
}


/**
 * @param $arr
 * @param $key_name
 * @return array
 * 将数据库中查出的列表以指定的 id 作为数组的键名
 */
function convert_arr_key($arr, $key_name)
{
    $arr2 = array();
    foreach ($arr as $key => $val) {
        $arr2[$val[$key_name]] = $val;
    }
    return $arr2;
}


/**
 * 获取数组中的某一列
 * @param type $arr 数组
 * @param type $key_name 列名
 * @return type  返回那一列的数组
 */
function get_arr_column($arr, $key_name)
{
    $arr2 = array();
    foreach ($arr as $key => $val) {
        $arr2[] = $val[$key_name];
    }
    return $arr2;
}


/**
 * 获取url 中的各个参数  类似于 pay_code=alipay&bank_code=ICBC-DEBIT
 * @param type $str
 * @return type
 */
function parse_url_param($str)
{
    $data = array();
    $parameter = explode('&', end(explode('?', $str)));
    foreach ($parameter as $val) {
        $tmp = explode('=', $val);
        $data[$tmp[0]] = $tmp[1];
    }
    return $data;
}


/**
 * 二维数组排序
 * @param $arr
 * @param $keys
 * @param string $type
 * @return array
 */
function array_sort($arr, $keys, $type = 'desc')
{
    $key_value = $new_array = array();
    foreach ($arr as $k => $v) {
        $key_value[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($key_value);
    } else {
        arsort($key_value);
    }
    reset($key_value);
    foreach ($key_value as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}


/**
 * @param 多维数组
 * @return array 一维数组
 */
function array_multi2single($array)
{
    static $result_array = array();
    foreach ($array as $value) {
        if (is_array($value)) {
            array_multi2single($value);
        } else
            $result_array [] = $value;
    }
    return $result_array;
}

/**
 * 友好时间显示
 * @param $time
 * @return bool|string
 */
function friend_date($time)
{
    if (!$time)
        return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小时前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m月d日 H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m月d日', $time);
                break;
            default:
                $fdate = date('Y年m月d日', $time);
                break;
        }
    }
    return $fdate;
}


/**
 * 返回状态和信息
 * @param $status
 * @param $info
 * @return array
 */
function arrayRes($status, $info, $url = "")
{
    return array("status" => $status, "info" => $info, "url" => $url);
}

/**
 * @param $arr
 * @param $key_name
 * @param $key_name2
 * @return array
 * 将数据库中查出的列表以指定的 id 作为数组的键名 数组指定列为元素 的一个数组
 */
function get_id_val($arr, $key_name, $key_name2)
{
    $arr2 = array();
    foreach ($arr as $key => $val) {
        $arr2[$val[$key_name]] = $val[$key_name2];
    }
    return $arr2;
}

/**
 *  自定义函数 判断 用户选择 从下面的列表中选择 可选值列表：不能为空
 * @param type $attr_values
 * @return boolean
 */
function checkAttrValues($attr_values)
{
    if ((trim($attr_values) == '') && ($_POST['attr_input_type'] == '1'))
        return false;
    else
        return true;
}


// 服务器端IP
function serverIP()
{
    return gethostbyname($_SERVER["SERVER_NAME"]);
}


/**
 * 自定义函数递归的复制带有多级子目录的目录
 * 递归复制文件夹
 * @param type $src 原目录
 * @param type $dst 复制到的目录
 */
//参数说明：
//自定义函数递归的复制带有多级子目录的目录
function recurse_copy($src, $dst)
{
    $now = time();
    $dir = opendir($src);
    @mkdir($dst);
    while (false !== $file = readdir($dir)) {
        if (($file != '.') && ($file != '..')) {
            if (is_dir($src . '/' . $file)) {
                recurse_copy($src . '/' . $file, $dst . '/' . $file);
            } else {
                if (file_exists($dst . DIRECTORY_SEPARATOR . $file)) {
                    if (!is_writeable($dst . DIRECTORY_SEPARATOR . $file)) {
                        exit($dst . DIRECTORY_SEPARATOR . $file . '不可写');
                    }
                    @unlink($dst . DIRECTORY_SEPARATOR . $file);
                }
                if (file_exists($dst . DIRECTORY_SEPARATOR . $file)) {
                    @unlink($dst . DIRECTORY_SEPARATOR . $file);
                }
                $copyrt = copy($src . DIRECTORY_SEPARATOR . $file, $dst . DIRECTORY_SEPARATOR . $file);
                if (!$copyrt) {
                    echo 'copy ' . $dst . DIRECTORY_SEPARATOR . $file . ' failed<br>';
                }
            }
        }
    }
    closedir($dir);
}

// 递归删除文件夹
function delFile($dir, $file_type = '')
{
    if (is_dir($dir)) {
        $files = scandir($dir);
        //打开目录 //列出目录中的所有文件并去掉 . 和 ..
        foreach ($files as $filename) {
            if ($filename != '.' && $filename != '..') {
                if (!is_dir($dir . '/' . $filename)) {
                    if (empty($file_type)) {
                        unlink($dir . '/' . $filename);
                    } else {
                        if (is_array($file_type)) {
                            //正则匹配指定文件
                            if (preg_match($file_type[0], $filename)) {
                                unlink($dir . '/' . $filename);
                            }
                        } else {
                            //指定包含某些字符串的文件
                            if (false != stristr($filename, $file_type)) {
                                unlink($dir . '/' . $filename);
                            }
                        }
                    }
                } else {
                    delFile($dir . '/' . $filename);
                    rmdir($dir . '/' . $filename);
                }
            }
        }
    } else {
        if (file_exists($dir)) unlink($dir);
    }
}


/**
 * @return array
 * 多个数组的笛卡尔积
 */
function combineDika()
{
    $data = func_get_args();
    $data = current($data);
    $cnt = count($data);
    $result = array();
    $arr1 = array_shift($data);
    foreach ($arr1 as $key => $item) {
        $result[] = array($item);
    }

    foreach ($data as $key => $item) {
        $result = combineArray($result, $item);
    }
    return $result;
}


/**
 * @param $arr1
 * @param $arr2
 * @return array
 * 两个数组的笛卡尔积
 */
function combineArray($arr1, $arr2)
{
    $result = array();
    foreach ($arr1 as $item1) {
        foreach ($arr2 as $item2) {
            $temp = $item1;
            $temp[] = $item2;
            $result[] = $temp;
        }
    }
    return $result;
}

/**
 * 将二维数组以元素的某个值作为键 并归类数组
 * array( array('name'=>'aa','type'=>'pay'), array('name'=>'cc','type'=>'pay') )
 * array('pay'=>array( array('name'=>'aa','type'=>'pay') , array('name'=>'cc','type'=>'pay') ))
 * @param $arr 数组
 * @param $key 分组值的key
 * @return array
 */
function group_same_key($arr, $key)
{
    $new_arr = array();
    foreach ($arr as $k => $v) {
        $new_arr[$v[$key]][] = $v;
    }
    return $new_arr;
}

/**
 * 获取随机字符串
 * @param int $randLength 长度
 * @param int $addtime 是否加入当前时间戳
 * @param int $includenumber 是否包含数字
 * @return string
 */
function get_rand_str($randLength = 6, $addtime = 1, $includenumber = 0)
{
    if ($includenumber) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    } else {
        $chars = 'abcdefghijklmnopqrstuvwxyz';
    }
    $len = strlen($chars);
    $randStr = '';
    for ($i = 0; $i < $randLength; $i++) {
        $randStr .= $chars[rand(0, $len - 1)];
    }
    $tokenvalue = $randStr;
    if ($addtime) {
        $tokenvalue = $randStr . time();
    }
    return $tokenvalue;
}

/**
 * CURL请求
 * @param $url 请求url地址
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug 调试开启 默认false
 * @return mixed
 */
function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false)
{
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if ($ssl) {
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    return $response;
    //return array($http_code, $response,$requestinfo);
}

/**
 * 过滤数组元素前后空格 (支持多维数组)
 * @param $array 要过滤的数组
 * @return array|string
 */
function trim_array_element($array)
{
    if (!is_array($array))
        return trim($array);
    return array_map('trim_array_element', $array);
}

/**
 * 检查手机号码格式
 * @param $mobile 手机号码
 */
function check_mobile($mobile)
{
    if (preg_match('/1[34578]\d{9}$/', $mobile))
        return true;
    return false;
}

/**
 * 检查邮箱地址格式
 * @param $email 邮箱地址
 */
function check_email($email)
{
    if (filter_var($email, FILTER_VALIDATE_EMAIL))
        return true;
    return false;
}


/**
 *   实现中文字串截取无乱码的方法
 */
function getSubstr($string, $start, $length)
{
    if (mb_strlen($string, 'utf-8') > $length) {
        $str = mb_substr($string, $start, $length, 'utf-8');
        return $str . '...';
    } else {
        return $string;
    }
}


/**
 * 判断当前访问的用户是  PC端  还是 手机端  返回true 为手机端  false 为PC 端
 * @return boolean
 */
/**
 *   * 是否移动端访问访问
 *   *
 *   * @return bool
 *   */
function _isMobile()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        return true;

    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA'])) {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile');
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            return true;
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}

//php获取中文字符拼音首字母
function getFirstCharter($str)
{
    if (empty($str)) {
        return '';
    }
    $fchar = ord($str{0});
    if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
    $s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284) return 'A';
    if ($asc >= -20283 && $asc <= -19776) return 'B';
    if ($asc >= -19775 && $asc <= -19219) return 'C';
    if ($asc >= -19218 && $asc <= -18711) return 'D';
    if ($asc >= -18710 && $asc <= -18527) return 'E';
    if ($asc >= -18526 && $asc <= -18240) return 'F';
    if ($asc >= -18239 && $asc <= -17923) return 'G';
    if ($asc >= -17922 && $asc <= -17418) return 'H';
    if ($asc >= -17417 && $asc <= -16475) return 'J';
    if ($asc >= -16474 && $asc <= -16213) return 'K';
    if ($asc >= -16212 && $asc <= -15641) return 'L';
    if ($asc >= -15640 && $asc <= -15166) return 'M';
    if ($asc >= -15165 && $asc <= -14923) return 'N';
    if ($asc >= -14922 && $asc <= -14915) return 'O';
    if ($asc >= -14914 && $asc <= -14631) return 'P';
    if ($asc >= -14630 && $asc <= -14150) return 'Q';
    if ($asc >= -14149 && $asc <= -14091) return 'R';
    if ($asc >= -14090 && $asc <= -13319) return 'S';
    if ($asc >= -13318 && $asc <= -12839) return 'T';
    if ($asc >= -12838 && $asc <= -12557) return 'W';
    if ($asc >= -12556 && $asc <= -11848) return 'X';
    if ($asc >= -11847 && $asc <= -11056) return 'Y';
    if ($asc >= -11055 && $asc <= -10247) return 'Z';
    return null;
}

/**
 * @param $money
 * @return mixed
 * @description 将金额数字转化为中文大写
 */
function toChineseNumber($money)
{
    $money = round($money, 2);
    $cnynums = array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
    $cnyunits = array("圆", "角", "分");
    $cnygrees = array("拾", "佰", "仟", "万", "拾", "佰", "仟", "亿");
    list($int, $dec) = explode(".", $money, 2);
    $dec = array_filter(array($dec[1], $dec[0]));
    $ret = array_merge($dec, array(implode("", cnyMapUnit(str_split($int), $cnygrees)), ""));
    $ret = implode("", array_reverse(cnyMapUnit($ret, $cnyunits)));
    return str_replace(array_keys($cnynums), $cnynums, $ret);
}

function cnyMapUnit($list, $units)
{
    $ul = count($units);
    $xs = array();
    foreach (array_reverse($list) as $x) {
        $l = count($xs);
        if ($x != "0" || !($l % 4)) $n = ($x == '0' ? '' : $x) . ($units[($l - 1) % $ul]); else $n = is_numeric($xs[0][0]) ? $x : '';
        array_unshift($xs, $n);
    }
    return $xs;
}

/**
 * @param $month
 * @param string $type
 * @return array
 * @description  根据几个月 获取结束的 年月日
 */
function getEndByMonth($month, $type = 'all')
{
    $nowArr = getdate();
    $date = date_create($nowArr['year'] . '-' . $nowArr['mon'] . '-' . $nowArr['mday']);  //当前的时间
    date_add($date, date_interval_create_from_date_string($month . ' month'));
    $date = date_format($date, "Y-m-d");
    list($end_y, $end_m, $end_d) = explode('-', $date);
    switch ($type) {
        case 'all':
            $arr = array('year' => $end_y, 'month' => $end_m, 'day' => $end_d);
            break;
        case 'y':
            $arr = array('year' => $end_y);
            break;
        case 'm':
            $arr = array('month' => $end_m);
            break;
        case 'd':
            $arr = array('day' => $end_d);
            break;
        default:
            $arr = array();

    }


    return $arr;
}

//判断一个字符串是否属于序列化后的数据
function is_serialized($data)
{
    $data = trim($data);
    if ('N;' == $data)
        return true;
    if (!preg_match('/^([adObis]):/', $data, $badions))
        return false;
    switch ($badions[1]) {
        case 'a' :
        case 'O' :
        case 's' :
            if (preg_match("/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data))
                return true;
            break;
        case 'b' :
        case 'i' :
        case 'd' :
            if (preg_match("/^{$badions[1]}:[0-9.E-]+;\$/", $data))
                return true;
            break;
    }
    return false;
}

/**
 * @param $str
 * @param string $pre
 * @param int $key
 * @return mixed
 * @description 正则分割字符串
 * 2017年5月16日 12:07:51
 */
function mj_explode($str, $pre = '', $key = 0)
{
    $arr = preg_split($pre, $str);

    return strtolower($arr[$key]);
}

function getUserInfo(Request $request, $userId)
{
    return $userId;
}

/**
 * @param $url
 * @return mixed
 * 获取网站首页title
 */
function getUrlTitle($url)
{
    $str = file_get_contents($url);

    preg_match('/<title>(.*)<\/title>/', $str, $arr);

    return $arr[1];

}

/**
 * @param $url
 * @description 从网址获取域名
 */
function findDomainByUrl($url)
{
    preg_match("/^(http:\/\/)?([^\/]+)/i", $url, $matches);

    $host = $matches[2];    // 从主机名中取得后面两段

    preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);

    echo "domain name is: {$matches[0]}\n";

}

/**
 * @param $dir
 * @return array
 * 获取文件目录里边的文件
 */
function getFileInFiles($dir)
{
    $arr = array();
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
//                echo "filename:" . $file . "<br>";
                $arr[] = $file;
            }
            closedir($dh);
        }
    }
    return $arr;
}

/**
 * @param $str
 * @param $from
 * @param string $to
 * @return string
 * @description  替换数字符串的里的指定的值
 */
function i_strtr($str, $from, $to = '')
{
    if (is_array($from)) {
        return strtr($str, $from);   //$arr = array("Hello" => "Hi", "world" => "earth");echo strtr("Hello world",$arr);
    } else {
        return strtr($str, $from, $to);   //echo strtr("Hilla Warld","ia","eo");  Hello World
    }
}

/**
 * @param null $user_agent 可选。规定 HTTP 用户代理的名称。默认是 $HTTP_USER_AGENT 的值。您可以通过设置 NULL 绕过该参数。
 * @param bool $return_array 可选。如果该参数设置为 true，本函数会返回一个数组而不是对象。
 * @return mixed
 */
function i_get_browser($user_agent = null, $return_array = true)
{
//    echo $_SERVER['HTTP_USER_AGENT'];   //Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)
    if (get_browser() != false) {
        return get_browser($user_agent, $return_array);
    }
}

/**
 * @param $str
 * @param int $num
 * @param string $symbol
 * @return string
 * @description 切割字符串
 */
function i_chunk_split($str, $num = 1, $symbol = '.')
{
    $str = chunk_split($str, $num, $symbol);
    return $str;
}

/**
 * @param $data
 * @param string $a
 * @return string
 * @description 去除base64 字符串的符号
 */
function base64_encode2($data, $a = "+/=")
{
    $l = strlen($a);
    if ($l === 3) {
        return strtr(base64_encode($data), "+/=", $a);
    } else if ($l === 2) {
        return rtrim(strtr(base64_encode($data), "+/", $a), '=');
    } else {
        throw new InvalidArgumentException("Argument #2 must be 2 or 3 bytes.");
    }
}

/**
 * @param $data
 * @param bool $strict
 * @param string $a
 * @return string
 */
function base64_decode2($data, $strict = false, $a = "+/=")
{
    $l = strlen($a);
    if ($l === 3) {
        return base64_decode(strtr($data, $a, "+/="), $strict);
    } else if ($l === 2) {
        return base64_decode(strtr($data, $a, "+/"), $strict);
    } else {
        throw new InvalidArgumentException("Argument #2 must be 2 or 3 bytes.");
    }
}

/**
 * @param $url
 * @param $data
 * @return mixed
 * 2017年6月7日 10:45:46
 */
function post($url, $data)
{

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //声明使用POST方式来进行发送
    curl_setopt($ch, CURLOPT_POST, 1);

    //发送什么数据呢
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    //忽略证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    curl_setopt($ch, CURLOPT_HEADER, 0);

    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    $output = curl_exec($ch);

    curl_close($ch);

    return $output;
}

/**
 * @param $url
 * @return mixed
 * 2017年6月7日 10:45:43
 */
function get($url)
{

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_HEADER, 0);

    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    $output = curl_exec($ch);

    curl_close($ch);

    return $output;
}
/**
+----------------------------------------------------------
 * 字符串截取，支持中文和其他编码
+----------------------------------------------------------
 * @static
 * @access public
+----------------------------------------------------------
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
+----------------------------------------------------------
 * @return string
+----------------------------------------------------------
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
{
    if(function_exists("mb_substr")){
        if ($suffix && strlen($str)>$length)
            return mb_substr($str, $start, $length, $charset)."...";
        else
            return mb_substr($str, $start, $length, $charset);
    }
    elseif(function_exists('iconv_substr')) {
        if ($suffix && strlen($str)>$length)
            return iconv_substr($str,$start,$length,$charset)."...";
        else
            return iconv_substr($str,$start,$length,$charset);
    }
    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("",array_slice($match[0], $start, $length));
    if($suffix) return $slice."…";
    return $slice;
}
/**
 * @param $string
 * @return mixed
 * 简单的函数删除评论从字符串
 */
function remove_comments(& $string)
{
    $string = preg_replace("%(#|;|(//)).*%", "", $string);
    $string = preg_replace("%/\*(?:(?!\*/).)*\*/%s", "", $string); // google for negative lookahead
    return $string;
}

/**
 * @param $str
 * @return int
 * utf8_strlen – 获得UTF8编码的字符串的长度
 */
function utf8_strlen($str)
{
    $count = 0;
    for ($i = 0; $i < strlen($str); $i++) {
        $value = ord($str[$i]);
        if ($value > 127) {
            $count++;
            if ($value >= 192 && $value <= 223) $i++;
            elseif ($value >= 224 && $value <= 239) $i = $i + 2;
            elseif ($value >= 240 && $value <= 247) $i = $i + 3;
            else die('Not a UTF-8 compatible string');
        }
        $count++;
    }
    return $count;
}

/**
 * @param null $string
 * @return int
 * 计算中文字符串长度
 */
function c_utf8_strlen($string = null)
{
// 将字符串分解为单元
    preg_match_all("/./us", $string, $match);
// 返回单元个数
    return count($match[0]);
}

/**
 * @param $path
 * @param $filemode
 * @return bool
 * @description 修改文件的   改进递归文件模式@ infosoft ....,这是一个小短，应处理的Linux文件系统的所有文件类型。这个可以批量更改文件或目录的权限  例：：：：：chmodr(0777)
 */
function chmodr($path, $filemode)
{
    if (!is_dir($path)) {
        return chmod($path, $filemode);
    }
    $dh = opendir($path);
    while (($file = readdir($dh)) !== false) {
        if ($file != '.' && $file != '..') {
            $fullpath = $path . '/' . $file;
            if (is_link($fullpath)) {   //is_link() 函数判断指定文件名是否为一个符号连接。  符号链接又叫软链接,是一类特殊的文件，这个文件包含了另一个文件的路径名(绝对路径或者相对路径)
                return FALSE;
            } elseif (!is_dir($fullpath) && !chmod($fullpath, $filemode)) {
                return FALSE;
            } elseif (!chmodr($fullpath, $filemode)) {
                return FALSE;
            }

        }
    }
    closedir($dh);
    if (chmod($path, $filemode)) {
        return TRUE;
    } else {
        return FALSE;
    }

}
